js index of()用法


含義:

indexOf() 方法可返回某個指定的字符串值在字符串中首次出現的位置。(工作中常用)

提示和注釋:

注釋:indexOf() 方法對大小寫敏感

注釋:如果要檢索的字符串值沒有出現,則該方法返回 -1。

實例

我們將在 "Hello world!" 字符串內進行不同的檢索:

<script type="text/javascript">    
var str="Hello world!";  
document.write(str.indexOf("Hello") + "<br />");  
document.write(str.indexOf("World") + "<br />"); 
document.write(str.indexOf("world"));    
</script>

 

以上代碼的輸出:

0  -1  6   

 

多數用途

可以用於郵箱是否正確的判斷,例如
<script type="text/javascript">    
if((yx.email.value.indexOf('@',0)==-1)||(yx.email.value.indexOf('.',0)==-1))
{
alter("郵箱地址錯誤");
yx.email.focus();
return false;
}
</script>

 

 另一個例子

在vue中的props

// 更好的做法!
props: {
  status: {
    type: String,
    required: true,
    validator: function (value) {
      return [
        'syncing',
        'synced',
        'version-conflict',
        'error'
      ].indexOf(value) !== -1
    }
  }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM