给定一组数字,我希望使用 javascript 的 .some() 方法来查找第一对镜像数字并返回该对。
例如[454,86,57,75,16,88]) 应该返回 [57,75]。如果没有相互镜像的数字,我想返回 [-1,-1]。我设法达到了如果有镜像编号,则返回编号的程度。但是,我无法让它返回 [-1,-1]。我哪里做错了?
var a=0
var b=0
arr=[13,15,19,32,49,61,73]
arr.some((x,i)=>{
a=arr[i]
b=arr[i+1]
b= switchIt(b)
if(a!==b){ //what if there are no mirror image numbers found?
a = -1
b = -1
}else{
return a==b
}
})
function switchIt(n){
n= n.toString()
n= n.split("")
var [x,y,z]=[n[0],n[1],n[2]]
n= [z,y,x]
n= n.join("")
n= parseInt(n)
return n
}
console.log([a,switchIt(b)])
最佳答案
Given an array of numbers, I wish to use javascript's .some() method to find the first pair of mirror image numbers and return the pair.
那不是什么
some
做。 some
返回一个 bool 值:谓词函数要么返回一个真值(所以 some
返回 true
),或者它从未返回一个真值(所以 some
返回 false
)。虽然你可以使用
some
你想要的,你真正想要的是find
(在 ES2015 中添加,但完全可填充/可填充)。这是一个更简单的例子:var a = [
{id: 1, value: "one"},
{id: 2, value: "two"},
{id: 3, value: "three"},
{id: 4, value: "four"},
{id: 5, value: "five"}
];
var entry = a.find(function(e) {
return e.id === 3;
});
console.log(entry);
为了完整起见,您可以使用
find
, 通过使用变量 some
谓词结束:var a = [
{id: 1, value: "one"},
{id: 2, value: "two"},
{id: 3, value: "three"},
{id: 4, value: "four"},
{id: 5, value: "five"}
];
var entry;
a.some(function(e) {
if (e.id === 3) {
entry = e;
return true;
}
});
console.log(entry);
……但我不建议这样做。这正是
find
是专为。
关于javascript - 如果在 javascript .some() 函数中不满足条件,则返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40526897/