[英]Check if Immutable.js map value contains char
我想知道是否有一种简单的方法来检查不可变的映射值是否包含某个字符。
基本上是在寻找https://facebook.github.io/immutable-js/docs/#/Map/includes,但是只匹配值上的整个单词。
现在,我遍历每个属性并检查值本身。
function mapContains(map, char) {
let contains = false;
map.forEach((val) => {
if(val.includes(char)) {
contains = true;
return false; //short circuits the foreach
}
});
return contains;
}
感谢您的提前答复。
我建议为此使用Map.prototype.some
。 一旦您的lambda返回真实值,它将短路并返回true
否则返回false
const { Map } = require('immutable')
const m = Map({a: 'one', b: 'two', c: 'three'})
m.some(v => /t/.test(v)) // true, at least one value has a 't'
m.some(v => /x/.text(v)) // false, no values contain an 'x'
// but be careful with automatic string coercion
/o/.test({}) // true, because String({}), '[object Object]', contains 'o'
如果您的地图将包含多个值类型 ,则在使用String.prototype
方法时要格外小心-即,我建议不要使用此类方法
const { Map } = require('immutable')
// mixed value type Map
const m = Map({a: 'one', b: 2, c: 3})
// CAUTION!
// reckless assumption that every value is a string (or has a .includes method)
m.some(v => v.includes('o')) // true, short-circuits on first value
m.some(v => v.includes('x')) // TypeError: v.includes is not a function
如果必须使用String.prototype.includes
,我建议您先进行type
检查
const { Map } = require('immutable')
const m = Map({a: 'one', b: 2, c: 3})
m.some(v => typeof v === 'string' && v.includes('o')) // true
m.some(v => typeof v === 'string' && v.includes('x')) // fase
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.