0在indexOf中是什么意思? [英] What does 0 mean in indexOf?

查看:65
本文介绍了0在indexOf中是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我编写一些JavaScript时,遇到了一个新代码"indexOf".阅读另一篇文章后,我认为它的行为如下所示,但它似乎不正确.有人可以帮我解释一下"indexOf"吗?

false = -1;true = 0或更多?

我试图将-1更改为0或更多,但是什么也没发生.只是为了更好地了解jquery/indexOf.

我现在所拥有的,

  $(this).closest(row)[td_word.indexOf(keyword)!== -1吗?'显示隐藏'](); 

从"td_word"中搜索"keyword"的匹配项,如果不是假(!== -1,因此为真)display:visible ;,如果不是true(false)display:hide;.

谢谢.

解决方案

array.indexOf(element)返回数组中元素的索引.还要阅读官方文档.>

它被设计为在元素不存在时返回 -1 ,因为 0 表示该元素位于第0个索引(第一个元素)中./p>

示例:

  var array = ['a','b','c','d','e'];array.indexOf('a')//0array.indexOf('c')//2array.indexOf('f')//-1,因为它不存在于数组中 


根据我的理解,我认为您认为 indexOf 用于检查数组中是否存在某个元素.那只是副作用". indexOf 的值,但其实际用法是获取数组中元素的索引.

While I am writing some JavaScript, I came across a new code "indexOf". After read another post I thought its behaviour is as shown below but it seems not true. Can someone kindly give me an explanation about "indexOf", please?

false = -1; true = 0 and more?

I have tried to change -1 to 0 and more but then nothing happens. Just to have a better understanding about jquery/indexOf.

what I have now,

$(this).closest(row)[td_word.indexOf(keyword) !== -1 ? 'show' : 'hide']();

it search for match(es) of "keyword" from "td_word", if it is not false (!== -1, thus true) display:visible;, if it is not true (false) display:hide;.

Thanks in advance.

解决方案

array.indexOf(element) returns the index of the element in the array. Read the official documentation as well.

It was designed to return -1 when the element doesn't exist, because 0 would mean that the element is in the 0th index (1st element).

Examples :

var array = ['a','b','c','d','e'];

array.indexOf('a') //0
array.indexOf('c') //2
array.indexOf('f') //-1, because it doesn't exist in array


From what I understand in your wording, I think that you think that indexOf is used to check if a certain element exists in an array. That is just a "side-effect" of indexOf but its actual usage is getting the index of an element in the array.

这篇关于0在indexOf中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆