我想知道是否有一种简单的方法来检查不可变的地图值是否包含某个字符。
基本上寻找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;
}
感谢您的回复。
答案 0 :(得分:2)
我建议您使用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