我如何从 Arrays of Arrays 中获取 1 的索引
How can i get index of 1 from Arrays of Array
我得到一个这样的数组 [[2,4],[7,32],[76,44],[34,22]...] 最多 100 个,我想得到 5 个数组所有数组中,每个数组中的索引为 1。我在数组中的每个项目中获得索引 1,但我如何获得五个不同的项目,我想要 select 3 个随机元素(加上第一个和最后一个)。谁能帮帮我。
我希望输出是这样的
4
44
30
77
66
这是我的代码
const items = [[2,4],[7,32],[76,44],[34,22],[10,30],[34,67],[90,13],[20,14],[78,77],[9,77],[44,66]]
items.map(item => console.log(item[1]))
更新 2.0
从 items 数组中取 3 个随机项目和第一个和最后一个项目,return 每个项目的索引 1。
items = [[2,4],[7,32],[76,44],[34,22],[10,30],[34,67],[90,13],[20,14],[78,77],[9,77],[44,66]]
function action(arr) {
const f = arr[0];
const l = arr[arr.length-1]
const a = arr.slice(1, arr.length-1)
const t = [];
for(i=0; i<3;i++) {
t.push(a[Math.floor(Math.random()*a.length)][1]);
}
return [f[1], ...t, l[1]];
}
console.log(action(items))
旧答案
slice()
是正确的方法。
const items = [[2,4],[7,32],[76,44],[34,22],[10,30],[34,67],[90,13],[20,14],[78,77],[9,77],[44,66]]
function action(arr, from, to) {
return arr.slice(from, to)
}
console.log(action(items, 1, 6));
我得到一个这样的数组 [[2,4],[7,32],[76,44],[34,22]...] 最多 100 个,我想得到 5 个数组所有数组中,每个数组中的索引为 1。我在数组中的每个项目中获得索引 1,但我如何获得五个不同的项目,我想要 select 3 个随机元素(加上第一个和最后一个)。谁能帮帮我。
我希望输出是这样的
4 44 30 77 66
这是我的代码
const items = [[2,4],[7,32],[76,44],[34,22],[10,30],[34,67],[90,13],[20,14],[78,77],[9,77],[44,66]]
items.map(item => console.log(item[1]))
更新 2.0
从 items 数组中取 3 个随机项目和第一个和最后一个项目,return 每个项目的索引 1。
items = [[2,4],[7,32],[76,44],[34,22],[10,30],[34,67],[90,13],[20,14],[78,77],[9,77],[44,66]]
function action(arr) {
const f = arr[0];
const l = arr[arr.length-1]
const a = arr.slice(1, arr.length-1)
const t = [];
for(i=0; i<3;i++) {
t.push(a[Math.floor(Math.random()*a.length)][1]);
}
return [f[1], ...t, l[1]];
}
console.log(action(items))
旧答案
slice()
是正确的方法。
const items = [[2,4],[7,32],[76,44],[34,22],[10,30],[34,67],[90,13],[20,14],[78,77],[9,77],[44,66]]
function action(arr, from, to) {
return arr.slice(from, to)
}
console.log(action(items, 1, 6));