我有一个二维数组
var years = [[-1,"0 years"], [1,"< 1 year"], [2,"1-3 years"], [3,"> 3 years"]];
我想根据用户输入来获取年数,这是-1,1,2,3
,我该如何使用Javascript完成此操作?
我正在尝试使用years[years_input]
,但没有得到正确的值。
答案 0 :(得分:2)
尝试一下,希望它能起作用
let years = [
[-1, "0 years"],
[1, "< 1 year"],
[2, "1-3 years"],
[3, "> 3 years"]
];
function getYear(year) {
return years.find(el => el.indexOf(year) > -1)[1]
}
console.log(getYear(-1))
console.log(getYear(1))
console.log(getYear(2))
console.log(getYear(3))
答案 1 :(得分:1)
您可以使用find()
方法。
var years = [[-1,"0 years"], [1,"< 1 year"], [2,"1-3 years"], [3,"> 3 years"]];
let input = +prompt('enter the index');
console.log(years.find(x => x[0] === input)[1])
答案 2 :(得分:1)
获取数组的第一个元素(对于find
之类的极端情况,您需要使用-1
):
const years = [[-1,"0 years"], [1,"< 1 year"], [2,"1-3 years"], [3,"> 3 years"]];
const index = 3;
const [, res] = years.find(([n]) => n == index);
console.log(res);
答案 3 :(得分:1)
您可以使用包括:
var years = [[-1,"0 years"], [1,"< 1 year"], [2,"1-3 years"], [3,"> 3 years"]];
var input = +prompt()
for(var i = 0; i < years.length; i++) {
if (years[i].includes(input)) {
console.log(years[i][1])
break
}
}
答案 4 :(得分:1)