编程中的一些困惑

一些常见的问题

  • 1.值的累加

  • 1.1.输入一段字符串,获得字符串的字符长度

var obj = {
	charSub(str, pos = 0) {
        let len = str.length;
        let charLength = 0;
        let subChars = [];
        let i = 0;
        do {
        	charLength += str.charCodeAt(i) > 255 ? 2 : 1;
            if (charLength <= pos) {
				subChars.push(str.charAt(i));            	
            }
        } while(++i < len)
        if (charLength > pos) {
            subChars.push('...');
        }
		console.log('subChars: ', subChars, charLength, pos);
        return subChars.join('');
    }
}
// test case
var rs = obj.charSub('1,', 3);
console.log('(1,) sub (3) result: ', rs);
var rs = obj.charSub('1,', 3);
console.log('(1,) sub (3) result: ', rs);
var rs = obj.charSub('1,', 2);
console.log('(1,) sub (2) result: ', rs);
// real use
var rs = obj.charSub('资助慈善公益性项目,资助慈善推广活动;向社会救助人群提供帮助;奖励慈善事奖励慈善事慈善事慈善事慈善事', 82);
console.log(rs);
  • 1.2.使用高阶函数
var obj = {
	charSub(str = '', pos = 0) {
		return str.split('').reduce((curVal, nowVal, index, array) => {
			let addLen = nowVal.charCodeAt(0) > 255 ? 2 : 1;
			let {result, len, isSetLastValue} = curVal;
			if (addLen < pos) {
				addLen += len;
				if (addLen <= pos) { // 如果加上nowVal, 还是小于pos时, 才会真正的累加
					result += nowVal;
				}
			} else {
				if (isSetLastValue !== true) {
					let hasSpare = index < array.length; // 判断后面还有没有值
					if (hasSpare) {
						result += '...';
					}
					isSetLastValue = true;
				}
			}

			curVal.isSetLastValue = isSetLastValue;
			curVal.result = result;
			curVal.len = addLen;
			return curVal;
		}, {
			isSetLastValue: false,
			result: '',
			len: 0
		}).result;
	}
}
  • 2.带有默认值的空对象

  • 2.1.直接赋值

var array = [{}, {}, {}];
  • 2.2.使用函数
var array = new Array(6).join(',').split(',').map((a, index) => arr[index] = {});
var array = new Array(6).toString().split(',').map((a, index) => arr[index] = {});
var array = new Array(6).fill({});