我正在使用Javascript(ES6) /FaceBook反应,并试图获得大小不同的数组的前3个元素。我想做Linq take(n)的等效。

在我的Jsx文件中我有以下内容:

var items = list.map(i => {
  return (
    <myview item={i} key={i.id} />
  );
});

然后得到我尝试的前3个项目

  var map = new Map(list);
    map.size = 3;
    var items = map(i => {
      return (<SpotlightLandingGlobalInboxItem item={i} key={i.id} />);
    });

这并没有起作用,因为map没有一个set函数。

你能帮帮我吗?


当前回答

举个简单的例子:

var letters = ["a", "b", "c", "d"];
var letters_02 = letters.slice(0, 2);
console.log(letters_02)

输出:["a", "b"]

var letters_12 = letters.slice(1, 2);
console.log(letters_12)

输出:[b]

注意:slice只提供一个浅拷贝,不修改原始数组。

其他回答

举个简单的例子:

var letters = ["a", "b", "c", "d"];
var letters_02 = letters.slice(0, 2);
console.log(letters_02)

输出:["a", "b"]

var letters_12 = letters.slice(1, 2);
console.log(letters_12)

输出:[b]

注意:slice只提供一个浅拷贝,不修改原始数组。

slice()方法将数组部分的浅拷贝返回到从开始到结束(不包括end)选择的新数组对象中,其中start和end表示该数组中项目的索引。原始数组将不会被修改。

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]

console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]

console.log(animals.slice(-2));
// expected output: Array ["duck", "elephant"]

console.log(animals.slice(2, -1));
// expected output: Array ["camel", "duck"]

知道更多

使用lodash, take函数,您可以通过以下方式实现:

_.take([1, 2, 3]);
// => [1]
 
_.take([1, 2, 3], 2);
// => [1, 2]
 
_.take([1, 2, 3], 5);
// => [1, 2, 3]
 
_.take([1, 2, 3], 0);
// => []

也许我错过了一些东西,但感觉像踢开了一扇门,建议使用splice()?当然,重要的是要记住这将修改数组。

const myArray = [ '一',' 2 ',' 3 ',' 4 ',' 5 ',' 6 ',' 7 ', ] myArray.splice (3) console.log (myArray) //期望输出:['one', 'two', 'three']

也可以获取数组中被保留元素之外的元素:

const myArray = [ '一',' 2 ',' 3 ',' 4 ',' 5 ',' 6 ',' 7 ', ] const afterFirstThree = myArray.splice(3) console.log (myArray) //期望输出:['one', 'two', 'three'] console.log (afterFirstThree) / /预期的输出:[“4”、“5”、“6”、“7”) //如果n大于myArray。整个数组的长度被保留,如果试图获取返回值,它将是一个空数组

可以使用数组索引进行过滤。

var months = ['Jan', 'March', 'April', 'June']; month = Months .filter((month,idx) => idx < 2) console.log(个月);