我正在使用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函数。

你能帮帮我吗?


当前回答

也许我错过了一些东西,但感觉像踢开了一扇门,建议使用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。整个数组的长度被保留,如果试图获取返回值,它将是一个空数组

其他回答

要获取数组的前n个元素,使用

const slicedArray = array.slice(0, n);

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"]

知道更多

(1, 2, 3, 4, 5, 6, 7, 8, 8]。slice(0,3) = While返回前3个元素。

答:(1、2、3)

工作原理:

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

虽然这个问题很老了,但到2021年,将会有一个完整的LINQ实现,用ECMAScript (javascript)的最新特性编写对象。

Github存储库是:https://github.com/IlanAmoyal/WebPartyLinq

举个简单的例子:

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只提供一个浅拷贝,不修改原始数组。