zilongxuan001 / LearnFreecode

0 stars 0 forks source link

Slasher Flick #299

Open zilongxuan001 opened 6 years ago

zilongxuan001 commented 6 years ago

挑战

按指定索引的位置,返回数组索引及索引后的数组元素。

代码


function slasher(arr, howMany) {
  // it doesn't always pay to be first

  var arrChop=arr.splice(0,howMany);

  return arr;
}

slasher(["burgers", "fries", "shake"], 1);

结果显示

image

帮助

Array.prototype.splice() Array.prototype.slice()

来源

https://www.freecodecamp.org/challenges/slasher-flick

zilongxuan001 commented 6 years ago

20180403 var arrChop=arr.splice(0,howMany);

该语句的意思是移除arr数组从索引号0开始,移除howMany个元素,转移给arrChop, 这样arr数据就剩下从howMany开始往后的元素。

zilongxuan001 commented 6 years ago

20180403 arr.splice()可以改变原数组的元素。

var months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// inserts at 1st index position
console.log(months);
// expected output: Array ['Jan', 'Feb', 'March', 'April', 'June']

months.splice(4, 1, 'May');
// replaces 1 element at 4th index
console.log(months);
// expected output: Array ['Jan', 'Feb', 'March', 'April', 'May']

months.splice(1, 0, 'Feb');是在原数组索引号为1的位置上插入Feb,且不删除元素,原来索引号为1的March自动后移。

months.splice(4, 1, 'May');是在原数组索引号为4的位置上插入May,且删除原来索引号为4的June