1. 程式人生 > 其它 >js-Array【基礎-01】slice(start,end) 切片

js-Array【基礎-01】slice(start,end) 切片

slice()方法:

  • 返回一個新的陣列物件;
  • 這一物件是一個由beginend決定的原陣列的淺拷貝(包括begin,不包括end);
  • 原始陣列不會被改變。

淺拷貝:

  • 修改原陣列,子陣列物件也會隨之改變
// 使用 slice 方法從 myCar 中建立一個 newCar。
var myHonda = { color: 'red', wheels: 4, engine: { cylinders: 4, size: 2.2 } };
var myCar = [myHonda, 2, "cherry condition", "purchased 1997"];
var newCar = myCar.slice(0, 2);

// 輸出 myCar、newCar 以及各自的 myHonda 物件引用的 color 屬性。 console.log(' myCar = ' + JSON.stringify(myCar)); console.log('newCar = ' + JSON.stringify(newCar)); console.log(' myCar[0].color = ' + JSON.stringify(myCar[0].color)); console.log('newCar[0].color = ' + JSON.stringify(newCar[0].color)); // 改變 myHonda 物件的 color 屬性.
myHonda.color = 'purple'; console.log('The new color of my Honda is ' + myHonda.color); //輸出 myCar、newCar 中各自的 myHonda 物件引用的 color 屬性。 console.log(' myCar[0].color = ' + myCar[0].color); console.log('newCar[0].color = ' + newCar[0].color);
 myCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2,
       
'cherry condition', 'purchased 1997'] newCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2] myCar[0].color = red newCar[0].color = red The new color of my Honda is purple myCar[0].color = purple newCar[0].color = purple

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/slice