栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

JavaScript是否具有类似“ range()”的方法来在提供的范围内生成范围?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JavaScript是否具有类似“ range()”的方法来在提供的范围内生成范围?

它适用于字符和数字,通过可选步骤前进或后退。

var range = function(start, end, step) {    var range = [];    var typeofStart = typeof start;    var typeofEnd = typeof end;    if (step === 0) {        throw TypeError("Step cannot be zero.");    }    if (typeofStart == "undefined" || typeofEnd == "undefined") {        throw TypeError("Must pass start and end arguments.");    } else if (typeofStart != typeofEnd) {        throw TypeError("Start and end arguments must be of same type.");    }    typeof step == "undefined" && (step = 1);    if (end < start) {        step = -step;    }    if (typeofStart == "number") {        while (step > 0 ? end >= start : end <= start) { range.push(start); start += step;        }    } else if (typeofStart == "string") {        if (start.length != 1 || end.length != 1) { throw TypeError("only strings with one character are supported.");        }        start = start.charCodeAt(0);        end = end.charCodeAt(0);        while (step > 0 ? end >= start : end <= start) { range.push(String.fromCharCode(start)); start += step;        }    } else {        throw TypeError("only string and number types are supported");    }    return range;}

jsFiddle。

如果您想扩展本机类型,则将其分配给

Array.range

var range = function(start, end, step) {    var range = [];    var typeofStart = typeof start;    var typeofEnd = typeof end;    if (step === 0) {        throw TypeError("Step cannot be zero.");    }    if (typeofStart == "undefined" || typeofEnd == "undefined") {        throw TypeError("Must pass start and end arguments.");    } else if (typeofStart != typeofEnd) {        throw TypeError("Start and end arguments must be of same type.");    }    typeof step == "undefined" && (step = 1);    if (end < start) {        step = -step;    }    if (typeofStart == "number") {        while (step > 0 ? end >= start : end <= start) { range.push(start); start += step;        }    } else if (typeofStart == "string") {        if (start.length != 1 || end.length != 1) { throw TypeError("only strings with one character are supported.");        }        start = start.charCodeAt(0);        end = end.charCodeAt(0);        while (step > 0 ? end >= start : end <= start) { range.push(String.fromCharCode(start)); start += step;        }    } else {        throw TypeError("only string and number types are supported");    }    return range;}console.log(range("A", "Z", 1));console.log(range("Z", "A", 1));console.log(range("A", "Z", 3));console.log(range(0, 25, 1));console.log(range(0, 25, 5));console.log(range(20, 5, 5));


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/432224.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号