我正在编写一个带有对象和数组的函数。我遍历数组,并使用该值作为键来查找对象。
我希望一旦找到1个值就停止循环并返回该值。运行该功能时,我总是不知所措。
const searchInObject = function(obj, keys) {
//if array => loop and return the first value that is found.
//if not array and type is string find in object
// if no array or undefined return default value
if (Array.isArray(keys)) {
keys.map(key => {
if (obj[key]) return obj[key];
})
}
};
const obj = {
a: '1',
b: '2'
};
console.log(searchInObject(obj, ['a', 'b']));
答案 0 :(得分:3)
只需遍历键并检查键是否在obj
中存在。如果是,则返回值
const searchInObject = function(obj, keys) {
if (!Array.isArray(keys))
return;
for (const key of keys) {
if (key in obj)
return obj[key]
}
};
const obj = { a: '1', b: '2' };
console.log(searchInObject(obj, ['a', 'b']));
答案 1 :(得分:1)
尝试一下:
const searchInObject = function(obj, keys) {
if (Array.isArray(keys)) { //if array => loop and return the first value that is found.
for(let i = 0; i < keys.length; i++){
if (obj[keys[i]]) return obj[keys[i]];
}
} else if (typeof keys === 'string') { //if not array and type is string find in object
return obj[keys];
} else { // if no array or undefined return default value
return "default value"; // change this to the default value you want
}
};
const obj = {
a: '1',
b: '2'
};
console.log(searchInObject(obj, ['a', 'b']));
答案 2 :(得分:1)
您可以改为使用Array.find()
函数。这将返回第一个找到的值;如果找不到任何内容,则返回undefined
。
const searchInObject = (obj, keys) => {
if (Array.isArray(keys))
return keys.find(key => obj.hasOwnProperty(key))
else return undefined;
}
console.log(searchInObject({a: '1', b: '2'}, ['a','b']))
答案 3 :(得分:1)
我想您想使用importances = tree.feature_importances_
#std = np.std([tree.feature_importances_ for tree in forest.estimators_],
# axis=0)
indices = np.argsort(importances)[::-1]
# Print the feature ranking
print("Feature ranking:")
for f in range(X.shape[1]):
print("%d. feature %d (%f)" % (f + 1, indices[f], importances[indices[f]]))
# Plot the feature importances of the forest
plt.figure()
plt.title("Feature importances")
plt.bar(range(X.shape[1]), importances[indices],
color="r", yerr=std[indices], align="center")
plt.xticks(range(X.shape[1]), [feature_cols[i] for i in indices])
plt.xlim([-1, X.shape[1]])
plt.show()
而不是filter
。
下面是代码:
map
以上代码即使在const searchInObject = function(obj, keys) {
if(keys instanceof Array) {
keys = keys.filter(key => {
// This will return undefined if key is not present in object
return obj[key];
});
// The filtered keys array will contain only existing keys
// If length of keys is non zero then just return the value with first key
// Else return -1 or any other value
return keys.length > 0 ? obj[keys[0]] : -1;
}
// If keys is not an array, return -1 (or anything else if you want to)
return -1;
};
中找到第一个keys
,仍然会遍历整个key
数组。要对其进行优化,不必使用obj
或map
,而可以迭代filter
并返回第一个现有值。
代码如下:
keys
答案 4 :(得分:0)
实际上,不可能使用 Map 函数中断其迭代。尝试使用for循环或尝试以下类似方法的更好方法。
return keys.map(key => {
if (obj[key]) return obj[key];
})[0]