简体   繁体   中英

Reference any element in array

I made a script that makes 3 array elements, each of which equal:

Number(prompt())

Then I make an if statement saying:

if (!arr[0] || !arr[1] || !arr[2]) {alert("invalid data")}

This is ok for a couple of elements, however if I want to add say 10 elements then adding a bunch of logical OR operators is sort of clunky.

So I'm wondering if there is a way to just tell the interpreter "if any element in the array is not a number then alert an error else do alert(a)". (If that makes sense?.)

I am aware of the 'in' operator/keyword but this seems to check an array element name against the array name to see if it exists in that array. This is not quite what I'm after however.

I've also seen that there is a some() property/function but am not that far into learning JS yet.

Full script fiddle: https://jsfiddle.net/hj56yhbm/

Thanks.

So I'm wondering if there is a way to just tell the interpreter "if any element in the array is not a number then alert an error else do alert(a)"

This is a use case for Array.prototype.some or Array.prototype.every :

if (theArray.some(function(e) { return typeof e !== "number"; })) {
    alert("Non-number found");
}
// Or
if (!theArray.every(function(e) { return typeof e === "number"; })) {
    alert("Non-number found");
}

It's a bit easier to read with an ES2015+ arrow function:

if (theArray.some(e => typeof e !== "number")) {
    alert("Non-number found");
}
// Or
if (!theArray.every(e => typeof e === "number")) {
    alert("Non-number found");
}

The predicate can be whatever you want it to be. Your predicate, !value , has two problems:

  1. The number 0 is falsy, so !0 is true
  2. Lots of non-number values are truthy (for instance, !"hi" is false )

That's why I'm using typeof above instead.

Also beware that Number(prompt()) will return 0 if the user didn't type any number (because Number("") is 0 ).

Something along these lines (ES6)

const ex1 = [1,2,3,"string"];
const ex2 = [1,2,3,4];

var areAllNumbersEx1 = ex1.every(e => typeof e === "number");
var areAllNumbersEx2 = ex2.every(e => typeof e === "number");

console.log(`Ex1 all numbers: ${areAllNumbersEx1}`); //outputs: Ex1 all numbers: false
console.log(`Exs all numbers: ${areAllNumbersEx2}`); //outputs: Ex2 all numbers: true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM