day2:js字符串方法includes的实现逻辑

49 阅读1分钟
String.prototype._includes = function(targetVal, startIndex = 0) {
        if(targetVal === '') {
            return true
        }
        let start = 0;
        const len = this.length;
        targetVal = String(targetVal);
        startIndex = +startIndex;
        if (startIndex <=0 ){
            start = 0;
        } else if (startIndex > 0) {
            start = startIndex;
        }

        let hasTargetVal = false;
        for(let i = start; i < len; i++) {
            const status = (this[i] === targetVal);
            if (status) {
                hasTargetVal = status;
                break;
            }
        }
        return hasTargetVal;
    }
    console.log('12345'._includes(1, 0));
    // 输出结果:true