Vue 字符串轉Function

#Vue 字符串轉Function
方法一: eval

/* 定義字符串類型方法 */
const func="(value)=>{console.log(value);return value}"  

/* 字符串轉Function */
str_to_func(func,value){
	return eval(func)(value)
}

/* 使用 */
str_to_func(func,1)

結果是控制檯輸出1

有些代碼檢查會報錯,但是不影響使用
ESLint: eval can be harmful. (no-eval)

方法二: new Function

/* 定義字符串類型方法 */
const func = 'console.log(value);return value'

/* 字符串轉Function */
str_to_func (func, value) {
  const Fn = new Function('value', func)
  return Fn(value)
}

/* 使用 */
str_to_func(func,1)

/* 也可以直接使用 */
const func = 'console.log(value);return value'
const Fn = new Function('value', func)
Fn(1)

結果也是控制檯輸出1

但是代碼檢查依舊會有問題
ESLint: The Function constructor is eval. (no-new-func)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章