英文:
Array.includes not working as string.includes
问题
string.includes 可以检测字符串中的字符,但 array.includes("a") 只能检测是否数组的第一个元素等于 "a",当数组的第一个元素等于 "ab" 时返回 false。
有没有办法在不使用函数和循环的情况下在数组中实现类似于 string.includes 的功能(1行代码)?谢谢
var array = ["a", "b"];
array.includes("a"); // 返回 true
var array = ["ab","b"];
array.includes("a"); // 返回 false
Var string = "ab";
string.includes("a"); // 返回 true
我理解你想要实现 string.includes 在数组中的功能,但不使用函数和循环。
英文:
I want something like string.includes it can detect character among string but array.includes("a") can only detect if array[0] = "a" and return false when array[0] = "ab"
Is there anyway i can achieve string.includes in array without function and loop (1 line code) ? Thanks
var array = ["a", "b"];
array.includes("a"); //return true
var array = ["ab","b"];
array.includes("a"); //return false
Var string = "ab";
string.includes("a"); //return true
I want string.includes working with array without function and loop
答案1
得分: 3
注意,下面的join
变体会在字符串匹配本身包含逗号时出现问题。
const array = ['ab', 'cd']
console.log(array.some(i => i.includes('a')))
// 或者
console.log(array.join().includes('a'))
这是您提供的代码段的翻译部分。
英文:
Note that the join
variant below will cause problems if the string match itself contains a comma.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const array = ['ab', 'cd']
console.log(array.some(i=>i.includes('a')))
// or
console.log(array.join().includes('a'))
<!-- end snippet -->
答案2
得分: 0
你可以将一个函数添加到 Array
原型中,并将其用作 includes
if (Array.prototype.includesString === undefined) {
/*
* 检查一个字符串数组是否包含包含指定字符串的项
* @param {string} str - 要在每个项中检查的子字符串
* @returns {boolean} 字符串数组中是否存在包含指定字符串的项
*/
Array.prototype.includesString = function (str) {
return this.some(item => item.includes(str));
};
}
const result = ['ab', 'cd'].includesString('a');
console.log(result);
英文:
You can add a function to Array
prototype and use it as includes
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
if (Array.prototype.includesString === undefined) {
/*
* Checks if a string[] contains a item which includes the str
* @param {string} str - sub-string to check within each item
* @returns {boolean} whether an item in the string[] contains the str
*/
Array.prototype.includesString = function (str) {
return this.some(item => item.includes(str));
};
}
const result = ['ab', 'cd'].includesString('a');
console.log(result);
<!-- end snippet -->
答案3
得分: -1
要处理这个,您可以使用"JSON.stringify()"方法将其转换为字符串,对于每个或所有项目都可以如此。这不是其原始用途,但在处理搜索操作时特别有用。
英文:
For handle this, you can stringify it for each of them or all of them, by using "JSON.stringify()" method. It's not the original use case of that but it's so useful especially handling searching actions.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论