Javascript if not indexof

.index Of ( )

Ищет вхождение элемента в массив или подстроки в строку и возвращает индекс.

Время чтения: меньше 5 мин

Обновлено 12 октября 2021

Кратко

Скопировать ссылку «Кратко» Скопировано

Этот метод служит для поиска. Он определён для массивов и строк.

При вызове нужно передать, что искать. Вернётся индекс первого найденного элемента или -1 , если ничего не нашлось.

Как пишется

Скопировать ссылку «Как пишется» Скопировано

Искомый элемент передаётся первым аргументом — array1 . index Of ( ‘иголка’ )

 const example = ['чебурашка', 'гена', 'шапокляк', 'лариска'] console.log(example.indexOf('гена'))// 1 const example = ['чебурашка', 'гена', 'шапокляк', 'лариска'] console.log(example.indexOf('гена')) // 1      

Как понять

Скопировать ссылку «Как понять» Скопировано

Для массивов: ищет переданный элемент в массиве. Если элемент один, то возвращает индекс этого элемента. Если элементов много — возвращает индекс первого подходящего элемента. Элемента в массиве нет — вернёт -1

 const haystack = ['Петя', 'Настя', 'Артур', 'Лена', 'Настя'] console.log(haystack.indexOf('Лена'))// 3console.log(haystack.indexOf('Настя'))// 1console.log(haystack.indexOf('Эдуард Аркадьевич'))// -1 const haystack = ['Петя', 'Настя', 'Артур', 'Лена', 'Настя'] console.log(haystack.indexOf('Лена')) // 3 console.log(haystack.indexOf('Настя')) // 1 console.log(haystack.indexOf('Эдуард Аркадьевич')) // -1      

Для строк: работает так же, как с массивами, но можно искать не только буквы в строке, но и подстроки. Например:

 const haystack = 'Мама мыла раму' console.log(haystack.indexOf('а'))// 1console.log(haystack.indexOf('мыла'))// 5console.log(haystack.indexOf('ё'))// -1 const haystack = 'Мама мыла раму' console.log(haystack.indexOf('а')) // 1 console.log(haystack.indexOf('мыла')) // 5 console.log(haystack.indexOf('ё')) // -1      

На практике

Скопировать ссылку «На практике» Скопировано

Николай Лопин советует

Скопировать ссылку «Николай Лопин советует» Скопировано

🛠 Найти индексы всех подходящих элементов

Скопировать ссылку «🛠 Найти индексы всех подходящих элементов» Скопировано

Чтобы найти индексы всех искомых элементов, используют второй аргумент. Он указывает, с какого места начинать поиск. Таким образом можно проигнорировать те элементы, которые уже нашли и начинать поиск сразу после них:

 const haystack = 'мама мыла раму'let lastResult // напечатаем индексы всех букв М во фразеwhile (lastResult !== -1)  lastResult = haystack.indexOf('м', lastResult + 1) if (lastResult !== -1)  console.log(lastResult) >> const haystack = 'мама мыла раму' let lastResult // напечатаем индексы всех букв М во фразе while (lastResult !== -1)  lastResult = haystack.indexOf('м', lastResult + 1) if (lastResult !== -1)  console.log(lastResult) > >      

🛠 index Of ( ) или includes ( )

Скопировать ссылку «🛠 indexOf() или includes()» Скопировано

Не используйте index Of ( ) для проверки вхождения элемента в массив/строку, для этого есть метод includes ( ) .

Раньше методом index Of ( ) часто проверяли, есть ли элемент в массиве. Эта задача проще, индекс здесь не нужен, но других методов для этого не было.

Поэтому в старых скриптах можно увидеть такой код:

 const guestList = ['Петя', 'Настя', 'Артур', 'Лена', 'Настя', 'Эммануил']const guest = // получаем откуда-нибудь имя гостя if (guestList.indexOf(guest) >= 0)  // пускаем на вечеринку> else  // отправляем домой> const guestList = ['Петя', 'Настя', 'Артур', 'Лена', 'Настя', 'Эммануил'] const guest = // получаем откуда-нибудь имя гостя if (guestList.indexOf(guest) >= 0)  // пускаем на вечеринку > else  // отправляем домой >      

🤖 Из-за того, что index Of ( ) возвращает индекс, в условии обязательно нужна проверка ( > = 0 или ! = = — 1 ). Если так не сделать, то появится неприятный баг: мы будем пускать на вечеринку всех, кроме первого гостя в списке.

Дело в том, что JavaScript интерпретирует ненулевые числа как истину ( true ) и будет запускать первую ветку if . А на первом госте index Of ( ) вернёт 0 , что считается ложным ( false ), и наш скрипт не пустит человека на вечеринку.

Источник

Javascript if not indexof

Last updated: Dec 26, 2022
Reading time · 4 min

banner

# Table of Contents

# Check if Array Doesn’t contain a Value in JavaScript

Use the logical NOT (!) operator to negate the call to the includes() method to check if an array doesn’t contain a value.

The negated call to the Array.includes() method will return true if the value is not in the array and false otherwise.

Copied!
const arr = ['a', 'b', 'c']; const notIncludesD = !arr.includes('d'); console.log(notIncludesD); // 👉️ true const notIncludesC = !arr.includes('c'); console.log(notIncludesC); // 👉️ false if (notIncludesC) console.log('✅ the value c is NOT contained in the array'); > else // 👇️ this runs console.log('⛔️ the value c is contained in the array'); > // --------------------------------------- // ✅ Check if an object is not contained in an array const arr2 = [id: 1>, id: 2>, id: 3>]; const notContained = arr2.every(obj => return obj.id !== 4; >); console.log(notContained); // 👉️ true

We used the logical NOT (!) operator to negate the calls to the Array.includes() method.

This approach allows us to check if a specific value is not contained in the array.

Our first example checks if the value d is not contained in the array and returns true .

Copied!
const arr = ['a', 'b', 'c']; const notIncludesD = !arr.includes('d'); console.log(notIncludesD); // 👉️ true const notIncludesC = !arr.includes('c'); console.log(notIncludesC); // 👉️ false

The string c is contained in the array, so the expression returns false .

Here are some more examples of using the logical NOT (!) operator.

Copied!
console.log(!true); // 👉️ false console.log(!false); // 👉️ true console.log(!'hello'); // 👉️ false console.log(!''); // 👉️ true console.log(!null); // 👉️ true

You can imagine that the logical NOT (!) operator first converts the value to a boolean and then flips the value.

The falsy values in JavaScript are: null , undefined , empty string, NaN , 0 and false .

If you have to perform the test often, define a reusable function.

Copied!
function notIncludes(array, value) return !array.includes(value); > const arr = ['a', 'b', 'c']; console.log(notIncludes(arr, 'c')); // 👉️ false console.log(notIncludes(arr, 'd')); // 👉️ true console.log(notIncludes(arr, 'z')); // 👉️ true

The notIncludes() function takes an array and a value as parameters and checks if the value is not contained in the array.

The function returns true if the value is not contained in the array and false otherwise.

You can also use the indexOf() method to check if a value is not contained in an array.

# Check if Array Doesn’t contain a Value using indexOf()

This is a two-step process:

  1. Use the indexOf() method to get the index of the value in the array.
  2. If the method returns -1 , the array doesn’t contain the value.
Copied!
const arr = ['a', 'b', 'c']; if (arr.indexOf('d') === -1) // 👇️ this runs console.log('The value d is NOT contained in the array'); > else console.log('The value d is contained in the array'); > console.log(arr.indexOf('c')); // 👉️ 2 console.log(arr.indexOf('z')); // 👉️ -1

The Array.indexOf method returns the index of the first occurrence of the supplied value in the array.

If the value is not contained in the array, the method returns -1 .

Our if statement checks if the Array.indexOf() method returned -1 .

If you have to perform the test often, define a reusable function.

Copied!
function notIncludes(array, value) return array.indexOf(value) === -1; > const arr = ['a', 'b', 'c']; console.log(notIncludes(arr, 'c')); // 👉️ false console.log(notIncludes(arr, 'd')); // 👉️ true console.log(notIncludes(arr, 'z')); // 👉️ true

The function takes an array and a value as parameters and returns true if the value is not contained in the array.

If you need to check if an object is not contained in an array, use the Array.every() method.

# Check if an object is not contained in an array in JavaScript

To check if an object is not contained in an array:

  1. Use the Array.every() method to iterate over the array.
  2. Check if each object doesn’t have a property equal to the specific value.
  3. The every() method will return true if the object is not in the array.
Copied!
const arr2 = [id: 1>, id: 2>, id: 3>]; const notContained = arr2.every(obj => return obj.id !== 4; >); console.log(notContained); // 👉️ true if (notContained) console.log('The object is NOT contained in the array'); > else console.log('The object is contained in the array'); >

The function we passed to the Array.every method gets called with each element of the array.

If all invocations of the callback function return a truthy value, then the Array.every() method returns true , otherwise, false is returned.

On each iteration, we check if the current object doesn’t have a specific value and return the result.

If the callback function we passed to the Array.every() method returns a falsy value, then Array.every() short-circuits also returning false .

If the Array.every() method returns true , then the object isn’t contained in the array.

If the method returns false , the object is contained in the array.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Check if a string contains a substring using indexOf() in JavaScript

To check if a string contains a substring in JavaScript:

  1. Call the String.indexOf() method on the given string, passing it to the substring as a parameter.
  2. Compare the returned value to -1 .
  3. If the returned value is not equal to -1 , the string contains the substring.
const str = 'React is a popular JavaScript library.' const substr = 'JavaScript' const index = str.indexOf(substr) console.log(index) // 19 if (str.indexOf(substr) !== -1)  console.log(`String contains "$substr>"`) > else  console.log(`String does not contain "$substr>"`) > // String contains "JavaScript" 

The String.indexOf(searchValue[, fromIndex]) method takes two parameters:

  1. searchValue — A string representing the value to search for within this string. If no string is explicitly specified, searchValue will default to undefined and this value will be searched in the current string.
  2. fromIndex — An optional integer that represents the index to start the search from. The default value is 0 .

The String.indexOf() method returns the index of the first occurrence of searchValue in the string, or -1 if not found. If an empty string is passed as searchValue , it will match at any index between 0 and str.length .

Note: In JavaScript, the first character in a string has an index of 0 , and the index of the last character is str.length — 1 .

Let us have another example:

const str = 'React is a popular JavaScript library.' str.indexOf('React') // 0 str.indexOf('Preact') // -1 str.indexOf('React', 5) // -1 str.indexOf('') // 0 str.indexOf('', 5) // 5 

The String.indexOf() method is case-sensitive, which means the following expressions evaluate to -1 :

'JavaScript'.indexOf('script') // -1 'JavaScript'.indexOf('SCRIPT') // -1 

If more than one matched substrings are present, String.indexOf() will return the first position of the first occurrence:

'Java, Java, Java!'.indexOf('Java') // 0 

The value 0 , returned by the String.indexOf() , method does not evaluate to true . The same is the case with -1 , which does not evaluate to false either.

So if you leave the equal operator to explicitly verify the presence of the string, you might see incorrect results.

Here is an interesting example:

const str = 'Apple is the manufacturer of iPhone X.' if(str.indexOf('Apple'))  console.log('Awesome!') > if(str.indexOf('Samsung'))  console.log('Good!') > 

In the above code, the first if condition will never execute even though the word Apple does exist in the string. Similarly, the second if condition will evaluate to true although the string does not contain the word Samsung .

For this reason, when checking if a string contains another substring, the correct way to check would be:

if (str.indexOf('Apple') !== -1)  console.log('Awesome!') > if (str.indexOf('Samsung') !== -1)  console.log('Good!') > 

Read this article to learn about other JavaScript functions that can be used to check the presence of a substring in a string.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

Читайте также:  Create file in memory java
Оцените статью