javascript - Find string in array using prototype functions -
i have array:
var str = "rrr"; var arr = ["ddd","rrr","ttt"];
i try check if arr contains str. try this:
var res = arr .find(str);
but on row above not works idea wrong?
find
(added in es2015, aka "es6") expects function predicate. you're looking indexof
:
var res = arr.indexof(str);
...which finds things comparing them ===
. you'll -1 if it's not found, or index if is.
in comment you've said:
no string exists expect null if exists expect true
...which seems bit odd (i'd think you'd want true
or false
), give that:
var res = arr.indexof(str) != -1 || null;
...because of javascript's curiously-powerful ||
operator (that's post on blog).
just completeness find
:
but can use find
; es5 version (in case you're polyfilling not transpiling):
var res = arr.find(function(entry) { return entry === str; });
or in es2015:
let res = arr.find(entry => entry === str);
res
null
if not found, str
if was. then, have str
, so... :-) find
more useful when you're searching for, say, object property value.
Comments
Post a Comment