将数组转换为逗号分隔的字符串

时间:2019-10-27 08:29:57

标签: javascript dom

add

classList方法仅接受字符串,而不接受数组(String [, String [, ...]]),所以我想知道是否存在一种优雅的方法来将数组转换为字符串列表,而又不明显循环播放:

var breakpoints = {
    "extraSmall"    : [ "only screen and (max-width: 575px)" ],
    "small"         : [ "only screen and (min-width: 576px) and (max-width: 767px)" ],
    "medium"        : [ "only screen and (min-width: 768px) and (max-width: 991px)" ],
    "large"         : [ "only screen and (min-width: 992px) and (max-width: 1199px)" ],
    "extraLarge"    : [ "only screen and (min-width: 1200px)" ],
}
Object.keys(breakpoints).map(feature => document.documentElement.classList.add(feature));

基本上,我希望在一个调用中添加多个类。

2 个答案:

答案 0 :(得分:2)

由于您不想创建新的数组,因此请勿使用.map。相反,您希望产生副作用,因此应该使用forEachfor循环:

for (const newClass of Object.keys(breakpoints)) {
  document.documentElement.classList.add(newClass)
}

为避免完全循环,可以(不明确地)与现有的className串联:

document.documentElement.className += ` ${Object.keys(breakpoints).join(' ')}`;

如果<html>标记尚没有类名,则不需要前导空格。如果事先不确定是否要使用类名,则可以改用classList.add

答案 1 :(得分:1)

由于add方法接受多个类作为参数,因此您可以在对象键上使用扩展语法...来将键中的每个元素作为类传递。

var breakpoints = { "extraSmall"    : [ "only screen and (max-width: 575px)" ], "small"         : [ "only screen and (min-width: 576px) and (max-width: 767px)" ], "medium"        : [ "only screen and (min-width: 768px) and (max-width: 991px)" ], "large"         : [ "only screen and (min-width: 992px) and (max-width: 1199px)" ], "extraLarge"    : [ "only screen and (min-width: 1200px)" ],}
const div = document.querySelector('div');
const classes = Object.keys(breakpoints);
div.classList.add(...classes);
<div>Div</div>

对于不支持传播语法的旧版浏览器,可以使用apply方法。

var breakpoints = { "extraSmall"    : [ "only screen and (max-width: 575px)" ], "small"         : [ "only screen and (min-width: 576px) and (max-width: 767px)" ], "medium"        : [ "only screen and (min-width: 768px) and (max-width: 991px)" ], "large"         : [ "only screen and (min-width: 992px) and (max-width: 1199px)" ], "extraLarge"    : [ "only screen and (min-width: 1200px)" ],}
const div = document.querySelector('div');
const classes = Object.keys(breakpoints);
div.classList.add.apply(div.classList, classes)
<div>Div</div>