Skip to content

字符串练习题

js
// 生成一个a-z的字符串
let str = ''
for (let i = 97; i <= 122; i++) {
    str += String.fromCharCode(i)
}
console.log(str)
js
// 将下面的字符串分割成一个单词数组,同时去掉数组中每一项的,和.
var str =
  'Lorem, ipsum dolor sit amet consectetur adipisicing elit. Adipisci impedit voluptatem cupiditate, est corporis, quis sunt quod tempore officiis hic voluptates eaque commodi. Repudiandae provident animi quia qui harum quasi.';

let result = str.split(" ");
for (let i = 0; i < result.length; i++) {
  result[i] = result[i].replaceAll(",", "").replaceAll(".", "");
}
console.log(result);
js
// 得到下面字符串中第一个i和最后一个i之间的子串

var str =
  'Lorem, ipsum dolor sit amet consectetur adipisicing elit. Adipisci impedit voluptatem cupiditate, est corporis, quis sunt quod tempore officiis hic voluptates eaque commodi. Repudiandae provident animi quia qui harum quasi.';

let firstI = str.indexOf("i");
let lastI = str.lastIndexOf("i");
let result = str.slice(firstI + 1, lastI);
console.log(result);
js
// 将下面的rgb格式转换成为HEX格式
var rgb = 'rgb(253, 183, 25)';

let parts = rgb.replaceAll('rgb', "").replaceAll("(", "").replaceAll(")", "").split(",");

let r = parseInt(parts[0]).toString(16);
let g = parseInt(parts[1]).toString(16);
let b = parseInt(parts[2]).toString(16);

let result = `#${r}${g}${b}`;
console.log(result);
js
// name转换成驼峰命名
var name = 'has own property'; // --> hasOwnProperty

let result = "";
let parts = name.split(" ");
for (let i = 0; i < parts.length; i++) {
    let s = parts[i];
    if (i > 0) {
        s = s[0].toUpperCase() + s.substring(1);
    }
    result += s;
}
console.log(result);

Math练习题

js
/**
 * 得到一个指定范围内的随机整数
 * @param {number} min 范围的最小值
 * @param {number} max 范围的最大值(无法取到最大值)
 * @return {number} 范围内的随机整数
 */
function getRandom(min, max) {
    return Math.floor(Math.random() * (max - min) + min);
}
js
function getRandom(min, max) {
    return Math.floor(Math.random() * (max - min) + min);
}

/**
 * 得到一个指定长度的随机字符串
 * 字符串包含:数字、字母
 * @param {number} length 字符串的长度
 * @return {number} 随机字符串
 */
function getRandomString(length) {
    var str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    let result = "";
    for (let i = 0; i < length; i++) {
        var index = getRandom(0, str.length);
        result += str[index];
    }
    return result

    // 方法二:巧办法
    // return Math.random().toString(36).substr(2, 2 + length);
}

let res = getRandomString(7);
console.log(res);
js
function getRandom(min, max) {
    return Math.floor(Math.random() * (max - min) + min);
}

/**
 * 从一个数组中随机取出一项
 * @param {any[]} arr 数组
 * @return {any} 数组的随机一项
 */
function getRandomItem(arr) {
    return arr[getRandom(0, arr.length)];
}

var arr = [2, 3, "abc", "h", 6];
console.log(getRandomItem(arr));

:::

MIT License