在写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