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

问题描述 投票:0回答:2

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));

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

javascript dom
2个回答
1
投票

由于您不想创建新的数组,因此请勿使用.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会更容易。


0
投票

您可以在...方法中使用扩展语法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');
div.classList.add(...Object.keys(breakpoints));
<div>Div</div>
© www.soinside.com 2019 - 2024. All rights reserved.