Sass 可以计算包含数学表达式的字符串吗? [英] Can Sass evaluate strings that contain mathematical expressions?

查看:37
本文介绍了Sass 可以计算包含数学表达式的字符串吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个函数,该函数将根据给定的表达式输出数字列表.

I'm trying to create a function which will output a list of numbers based on an expression given to it.

有谁知道我如何通过函数传递表达式并在函数内对其求值?

Does anyone know how I can pass an expression through a function and have it evaluated within the function?

这是我目前所拥有的:

@function patt($expression, $b: 10) {
    $result: ();
    @for $i from 1 through 10 {
        $result: append($result, unquote($expression));
    }
    @return $result;
}

示例用法:

$list: patt('$i * $b + 2');

不幸的是,这不起作用.据推测,该表达式在函数中被视为字符串.

Unfortunately this doesn't work. Presumably the expression is being treated as a string within the function.

推荐答案

没有.Sass 没有 eval 函数.最接近的是使用 call 函数.

No. Sass does not have an eval function. The closest you can get is by using the call function.

@function my-expression($x, $y) {
  @return $x * $y + 2;
}

@function patt($expression, $b: 10) {
    $result: ();
    @for $i from 1 through 10 {
        $result: append($result, call($expression, $i, $b));
    }
    @return $result;
}

$list: patt('my-expression'); // 12 22 32 42 52 62 72 82 92 102

这篇关于Sass 可以计算包含数学表达式的字符串吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆