endsWith is not a function解決方案

在寫javascript腳本時,用某些方法,有時候會碰到"XXX is not a function"之類的報錯.javascript

出現這種狀況,主要是由於某些方法在低版本瀏覽器上不支持。好比說"endsWith is not a fucntion".在ES5裏面,string對象是沒有endsWith 方法的。java

 

這裏能夠提供2中方法解決。瀏覽器

1、用lastindexOf(此方法基於對原型掌握不熟練的時候用)。this

思路以下:prototype

var str="5555str";code

var str2 ="str";對象

//str1 是否以str2結尾索引

function(str1,str2){ip

if(str1.lenth<str2.length){字符串

return false;

}

var len = str1.lenth - str2.length;

if((str1.lastIndexOf(str2)>-1)&&len===str1.lastIndexOf(str2)){

return len;//若是是以str2結尾,則返回其在str1的索引值

}else{

return false;/

}

}

 

2、修改String.prototype

if (!String.prototype.endsWith) {
//判斷String這個對象原型是否有endsWith方法,沒有的話,就用加上這個方法 Object.defineProperty(String.prototype, 'endsWith', { enumerable: false, configurable: false, writable: false, value: function (searchString, position) { position = position || this.length; position = position - searchString.length; var lastIndex = this.lastIndexOf(searchString); return lastIndex !== -1 && lastIndex === position; } });

用了這個方法後,字符串的實例都會從從String對象的原型找到endsWith這個方法。

 

固然,方法二更優。

參考處:

http://stackoverflow.com/questions/18768344/javascript-endswith-function-not-working

相關文章
相關標籤/搜索