所以JavaScript是一种函数式语言,类是从函数定义的,函数作用域对应于类构造函数.经过相当长的一段时间研究如何在JavaScript中进行OOP,我现在都得到了它.
我想做的不一定是可能的,所以我首先想知道这是不是一个好主意.所以,假设我有一个数组和类如下:
var Entry = function(name, numbers, address) {
this.name = name;
if(typeof numbers == "string") {
this.numbers = [];
this.numbers.push(numbers);
}
else this.numbers = numbers;
this.address = address;
};
var AddressBook = [];
Run Code Online (Sandbox Code Playgroud)
我添加了以下功能的联系人:
function addContact(name, numbers, address) {
AddressBook.push(new Entry(name, numbers, address));
}
Run Code Online (Sandbox Code Playgroud)
我不能这样做new Entry()会让自己陷入困境AddressBook吗?如果我不能在创建时执行此操作,那么使用Entry原型中的方法来完成它将会很有趣.我无法想办法做任何类似的事情.
我正在做一个练习(来自 Beginning Javascript)以更好地理解 DOM 操作。尝试仅使用 JS 以 DRY 方法重新创建下表(教科书解决方案在这里):
<table>
<tr>
<td>Car</td>
<td>Top Speed</td>
<td>Price</td>
</tr>
<tr>
<td>Chevrolet</td>
<td>120mph</td>
<td>$10,000</td>
</tr>
<tr>
<td>Pontiac</td>
<td>140mph</td>
<td>$20,000</td>
</tr>
</table>
Run Code Online (Sandbox Code Playgroud)
我尝试了这个,但不确定如何循环变量创建而不抛出错误:
var array = [['Car', 'Top Speed', 'Price'],['Chevrolet', '120mph', '$10,000'], ['Pontiac', '140pmh', '$20,000']] // Creating a data array which a loop will source from
var table = document.createElement('table');
document.body.appendChild(table); // Drew the main table node on the document
for (var i = 0; i<3; i++) {
var tr[i] = document.createElement('tr'); //Create …Run Code Online (Sandbox Code Playgroud) 可重现的例子
cats <-
data.frame(
name = c(letters[1:10]),
weight = c(rnorm(5, 10, 1), rnorm(5, 20, 3)),
type = c(rep("not_fat", 5), rep("fat", 5))
)
get_means <- function(df, metric, group) {
df %>%
group_by(.[[group]]) %>%
mutate(mean_stat = mean(.[[metric]])) %>%
pull(mean_stat) %>%
unique()
}
get_means(cats, metric = "weight", group = "type")
Run Code Online (Sandbox Code Playgroud)
我试过的
我希望得到两个值,而不是我得到一个值。看来 groupby 失败了。
我尝试了所有方法,包括使用 quo()、eval() 和替换 ()、UQ()、!! 以及许多其他方法来尝试使 group_by() 中的内容起作用。
这看起来非常简单,但我无法弄清楚。
代码推理
将变量放在引号中的决定是因为我在 ggplot aes_string() 调用中使用它们。我在函数中排除了 ggplot 代码以简化代码,否则会很容易,因为我们可以使用标准评估。
我在MDN、一本书等地方阅读了语法和使用,但无法实现标签的实用价值。也许是搜索引擎?
语境
作为R的后续版本:通过引用函数以及如何在函数内的数据框中添加列来传递data.frame
我正在尝试以下看似简单的功能:
naToZero <- function(df) {
df$Vol[is.na(df$Vol)] <- 0
}
数据框
> str(WFM)
Classes ‘tbl_df’, ‘tbl’ and 'data.frame': 990571 obs. of 14 variables:
$ Date : chr "04/12/2017" "04/12/2017" "04/12/2017" "04/12/2017" ...
$ Time :Classes 'hms', 'difftime' atomic [1:990571] 41970 41969 41968 41967 41966 ...
.. ..- attr(*, "units")= chr "secs"
$ Bar# : chr "197953/197953" NA "197952/197953" NA ...
$ Bar Index : int 0 NA -1 NA NA -2 NA NA …Run Code Online (Sandbox Code Playgroud)