最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

arrays - Javascript 'if' statement using .includes() - Stack Overflow

programmeradmin1浏览0评论

I have an array containing file paths as strings. I need to search through this array & make a new array including only those which contain a certain word. How would I create an if statement that includes the 'includes' method?

Here's my code so far:

var imagePaths = [...]

if(imagePaths.includes('index') === 'true'){
 ???
}

Thank you in advance

I have an array containing file paths as strings. I need to search through this array & make a new array including only those which contain a certain word. How would I create an if statement that includes the 'includes' method?

Here's my code so far:

var imagePaths = [...]

if(imagePaths.includes('index') === 'true'){
 ???
}

Thank you in advance

Share Improve this question asked Jul 12, 2017 at 18:35 r_cahillr_cahill 6073 gold badges10 silver badges20 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 13

You don't need to compare booleans to anything; just use them:

if (imagePaths.includes('index')) {
    // Yes, it's there
}

or

if (!imagePaths.includes('index')) {
    // No, it's not there
}

If you do decide to compare the boolean to something (which in general is poor practice), compare to true or false, not 'true' (which is a string).

'true' != true:

if (imagePaths.includes('index') === true) {
 ???
}

Or, which is way better, just use the value directly, since if already checks if the expression it receives is equal to true:

if (imagePaths.includes('index')) {
 ???
}

In Javascript, to make a new array based on some condition, it's better to use array.filter method.

Ex:

var imagePaths = [...];

var filterImagePaths = imagePaths.filter(function(imagePath){

//return only those imagepath which fulfill the criteria

   return imagePath.includes('index');

});
发布评论

评论列表(0)

  1. 暂无评论