如果我有一个数组,其中包含三个数组,并且想要提取每个数组中索引[1]的内容
Array(4) [Array(3), Array(3), Array(1), Array(1)]
length:4
[
0:Array(3) ["cfdb9868-0f69-5781-b1e4-793301280788", "127.0.0.1", "9146"] // Extract content of Index[0]
1:Array(3) ["cfdb9868-0f69-5781-b1e4-793301280788", "127.0.0.1", "9146"] // Extract content of Index[0]
2:Array(1) ["b32f4c08-8d53-5fed-8034-4bfb144dfe10"] // Extract content of Index[0]
3:Array(1) ["b32f4c08-8d53-5fed-8034-4bfb144dfe10"] // Extract content of Index[0]
]
在每一行中我只想提取第一个变量,这是我的结果:
let result = [
["cfdb9868-0f69-5781-b1e4-793301280788"],["cfdb9868-0f69-5781-b1e4-793301280788"],
["b32f4c08-8d53-5fed-8034-4bfb144dfe10"],["b32f4c08-8d53-5fed-8034-4bfb144dfe10"]
]
我使用切片和分割只有第一个,但给我错误函数
最佳答案
非常简单的解决方案,使用 Array.prototype.map
属性(property)
const input = [
["cfdb9868-0f69-5781-b1e4-793301280788", "127.0.0.1", "9146"],
["cfdb9868-0f69-5781-b1e4-793301280788", "127.0.0.1", "9146"],
["b32f4c08-8d53-5fed-8034-4bfb144dfe10"],
["b32f4c08-8d53-5fed-8034-4bfb144dfe10"]
]
const output = input.map(([firstElement])=>[firstElement])
console.log(output)
存储第 n 个变量有点复杂
const input = [
["cfdb9868-0f69-5781-b1e4-793301280788", "127.0.0.1", "9146"],
["cfdb9868-0f69-5781-b1e4-793301280788", "127.0.0.1", "9146"],
["b32f4c08-8d53-5fed-8034-4bfb144dfe10"],
["b32f4c08-8d53-5fed-8034-4bfb144dfe10"]
]
const output = (n) => input.map((element)=> element[n] ? [element[n]] : [])
console.log("0", JSON.stringify(output(0)))
console.log("1", JSON.stringify(output(1)))
console.log("2", JSON.stringify(output(2)))
假设如果不存在具有给定索引的元素,您可能不想保留空数组,您可以像这样修改上面的代码:
const input = [
["cfdb9868-0f69-5781-b1e4-793301280788", "127.0.0.1", "9146"],
["cfdb9868-0f69-5781-b1e4-793301280788", "127.0.0.1", "9146"],
["b32f4c08-8d53-5fed-8034-4bfb144dfe10"],
["b32f4c08-8d53-5fed-8034-4bfb144dfe10"]
]
const output = (n) => input.reduce((list, element)=> element[n] ? [...list, element[n]] : list, [])
console.log("0", JSON.stringify(output(0)))
console.log("1", JSON.stringify(output(1)))
console.log("2", JSON.stringify(output(2)))
关于javascript - 提取每个数组中第一个 Index[0] 的内容如果我有一个数组并且其中有多个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60321003/